<template>
  <div class="page-wrapper no-padding">
    <tree-list :path="selectPath" :show-level="1" @file-select="fileSelect"></tree-list>
    <div class="camera-wrapper">
      <c-card title="视频监控" class="camera-card">
        <el-button slot="func" size="small" @click="showAddDlg">添加设备</el-button>
        <h3 v-if="!selectPath">请选择变电站...</h3>
        <template v-else>
          <div class="camera-list">
            <h3 v-if="cameraList instanceof Array && cameraList.length === 0">无数据...</h3>
            <div v-for="c in cameraList" :key="c.pkid" class="camera-item">
              <img src="@/assets/background/background.jpg" alt @click.self="openCamera(c)" />
              <div class="camera-name row">
                <span>{{ c.cameraName }}</span>
                <span style="height: 20px">
                  <img
                    src="../../assets/icon/icon_edit.png"
                    alt="edit"
                    title="编辑"
                    @click="showEditDlg(c)"
                  />
                  <img
                    src="../../assets/icon/delete.png"
                    alt="delete"
                    title="删除"
                    @click="delHandle(c.pkid)"
                  />
                </span>
              </div>
            </div>
          </div>
          <div class="pagination">
            <el-pagination
              layout="prev, pager, next"
              :page-size="page.size"
              :current-page.sync="page.index"
              :total="page.total"
              @current-change="_getList"
            ></el-pagination>
          </div>
        </template>
      </c-card>
    </div>
    <c-dlg :visible.sync="visible" :title="curCamera.pkid ? '编辑设备' : '添加设备'" :type="2">
      <el-form
        ref="form"
        :model="curCamera"
        :rules="rules"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="名称" prop="cameraName">
              <el-input v-model="curCamera.cameraName" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="视频地址" prop="liveIP">
              <el-input v-model="curCamera.liveIP" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="类型" prop="cType">
              <el-select v-model="curCamera.cType" size="small">
                <el-option label="海康" :value="1"></el-option>
                <el-option label="其他" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="码流类型" prop="streamType">
              <el-select v-model="curCamera.streamType" size="small">
                <el-option label="主码" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="通道号" prop="channelId">
              <el-input v-model="curCamera.channelId" size="small"></el-input>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="端口" prop="remotePort">
              <el-input v-model="curCamera.remotePort" size="small"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row last-row">
          <div class="row-item">
            <el-form-item label="登录名" prop="remoteUser">
              <el-input v-model="curCamera.remoteUser" size="small"></el-input>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="密码" prop="remotePwd">
              <el-input v-model="curCamera.remotePwd" size="small" type="password"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="submitForm">提交</el-button>
        <el-button @click="cancleDlg">取消</el-button>
      </div>
    </c-dlg>
  </div>
</template>

<script>
import TreeList from "../data/components/TreeList";
import CCard from "@/components/CCard";
import CDlg from "@/components/CDlg";
import Spliter from "@/components/Spliter";
import { getList, getVideoUrl, saveCamera, delCamera } from "@/api/camera";
import { cloneDeep } from "lodash";
// import Video from "video.js";
export default {
  name: "Camera",
  components: {
    TreeList,
    CCard,
    CDlg,
    Spliter
  },
  data() {
    return {
      selectPath: null,
      curId: null,
      page: {
        index: 1,
        size: 9,
        total: 0
      },
      cameraList: [],
      urls: [],
      curCameraId: null,
      curCamera: {},
      visible: false,
      options: {
        autoplay: true,
        preload: "auto",
        width: "100%",
        height: "100%",
        poster: "MY_VIDEO_POSTER.jpg"
      },
      rules: {
        cameraName: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        liveIP: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        cType: [{ required: true, message: "该字段不能为空", trigger: "blur" }],
        streamType: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        channelId: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        remotePort: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        remoteUser: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        remotePwd: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    curUrl() {
      const a = this.urls.find(u => u.cameraId === this.curCameraId);
      return a && a.url;
      // return a && a.url.replace('http://', 'https://')
    }
  },
  watch: {
    selectPath: {
      handler(v) {
        const id = v[v.length - 1];
        const path = this.$route.path;
        this.$router.push(path + "?id=" + id);
      },
      deep: true
    },
    $route: {
      handler(v) {
        const id = v.query.id;
        if (id) {
          if (!this.selectPath) {
            this.selectPath = [];
            this.selectPath.push(id);
          }
          this.curId = parseInt(id.substr(1));
          this._getList();
        }
      },
      immediate: true
    }
  },
  methods: {
    fileSelect(path) {
      this.selectPath = path;
    },
    _getList() {
      const post = {
        substationId: this.curId,
        pageNo: this.page.index,
        pageSize: this.page.size
      };
      return getList(post)
        .then(data => {
          this.$set(this.page, "total", data.total || 0);
          this.cameraList = data.rows;
        })
        .catch(e => this.$message.error(e));
    },
    openCamera(c) {
      this.curCamera = c;
      const cip = c.liveIP;
      if (!cip) {
        return this.$message.error("数据异常!!");
      }
      if (cip.endsWith(".m3u8")) {
        // const code = c.cameraCode;
        let path = "/camera/display?path=" + cip;
        if (process.env.NODE_ENV === "production") {
          path = "http://huapu-power.com/plat/#/camera/display?path=" + cip;
          return window.open(path);
        }
        return this.$router.push(path);
      }
      const code = cip.substr(cip.indexOf("=") + 1);
      getVideoUrl(code).then(data => {
        let path = "/camera/display?path=" + data.url;
        if (process.env.NODE_ENV === "production") {
          path =
            "http://huapu-power.com/plat/#/camera/display?path=" + data.url;
          return window.open(path);
        }
        return this.$router.push(path);
      }).catch(() => {
        this.$message.error('解析视频地址失败')
      })
    },
    showEditDlg(row) {
      this.visible = true;
      if (this.curCamera.pkid !== row.pkid) {
        this.curCamera = cloneDeep(row);
      }
    },
    showAddDlg() {
      this.visible = true;
      if (this.curCamera.pkid) {
        this.curCamera = {};
      }
      if (!this.curCamera.cType) {
        this.curCamera.cType = 1;
      }
      if (!this.curCamera.substationId) {
        this.curCamera.substationId = this.curId;
      }
      if (!this.curCamera.streamType) {
        this.curCamera.streamType = 1;
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          return saveCamera(this.curCamera)
            .then(() => {
              this._getList();
              this.cancleDlg();
            })
            .catch(e => {
              this.$message.error(e);
            });
        }
      });
    },
    cancleDlg() {
      this.curCamera = {};
      this.visible = false;
    },
    delHandle(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delCamera(id)
          .then(() => {
            this._getList();
          })
          .catch(e => this.$message.error(e));
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page-wrapper {
  height: 100%;
  margin: 0;
  .camera-wrapper {
    margin-left: 275px;
    overflow-y: auto;
    height: 100%;
    box-sizing: border-box;
    display: flex;
  }
  .camera-card {
    margin: 20px;
  }
  .camera-list {
    flex: 1;
    display: grid;
    grid-gap: 10px;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 11vw);
    overflow-y: auto;
  }
  .camera-item {
    position: relative;
    // height: 11vw;
    cursor: pointer;
    border-radius: 4px;
    overflow: hidden;
    img {
      height: 100%;
      width: 100%;
    }
    .camera-name {
      cursor: default;
      margin: 0;
      color: #fff;
      position: absolute;
      width: 100%;
      box-sizing: border-box;
      padding-left: 10px;
      font-size: 14px;
      background: rgba($color: #000000, $alpha: 0.4);
      line-height: 20px;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 20px;
      align-items: center;
      img {
        cursor: pointer;
        height: 20px;
        width: auto;
        margin: 0;
        padding: 0;
      }
    }
  }
  .video-wrapper {
    width: 70vw;
    height: 60vh;
    position: relative;
    margin: -20px;
    #my-video {
      height: 100%;
      width: 100%;
    }
  }
}
</style>
